package com.cwx.web.admin;

import com.cwx.pojo.Type;
import com.cwx.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/admin")
public class TypeController {

    @Autowired
    private TypeService typeService;

    //分类列表首页
    @GetMapping("/types")
    public String type(@PageableDefault(size = 3,sort = {"id"},direction = Sort.Direction.DESC)Pageable pageable, Model model){
        Page<Type> types = typeService.listType(pageable);
        model.addAttribute("page",types);
        return "admin/types";
    }

    //页面跳转
    @GetMapping("/input")
    public String input(Model model){
        model.addAttribute("type",new Type());
        return "admin/types-input";
    }

    //添加一个新的分类
    @PostMapping("/addTypes")
    public String addTypes(Type type,RedirectAttributes attributes){
        Type type1 = typeService.saveType(type);
        if (type1 != null){
            attributes.addFlashAttribute("message","添加分类成功");
        }
       return "redirect:/admin/types";
    }

    //前端AJAX请求
    @GetMapping("/name")
    @ResponseBody
    public String name(String name){
        Type type = typeService.getType(name);
        if (type== null){
            return "true";
        }else {
            return "false";
        }
    }

    //编辑一个用户
    @GetMapping("/types/{id}/input")
    public String editor(@PathVariable Long id,Model model){
        model.addAttribute("type",typeService.getTypeById(id));
        return "admin/type-editor";
    }


    //编辑用户请求
    @PostMapping("/addTypes/{id}")
    public String editorType(@PathVariable Long id,Type type){
        typeService.updateType(id,type);
        return "redirect:/admin/types";
    }

    //删除一个用户
    @GetMapping("/types/{id}/delete")
    public String delete(@PathVariable Long id){
        typeService.deletedType(id);
        return "redirect:/admin/types";
    }
}
